using System;
using System.Globalization;
using System.Security;
using System.Runtime.InteropServices;
#if !PocketPC && Framework20
using System.Runtime.ConstrainedExecution;
#endif
#if !PocketPC || Framework20
using Microsoft.Win32;
#endif
using GeoFramework;

namespace GeoFramework.IO
{
    public sealed class SafeFileHandle : SafeHandle 
    {
		private bool pIsInvalid = true;
       
        private SafeFileHandle() 
            : base(IntPtr.Zero, true)
        {}        

		public SafeFileHandle(IntPtr handle, bool ownsHandle)
			: base(IntPtr.Zero, ownsHandle)
		{
			// Determine whether the handle is valid or not
			int HandleValue = handle.ToInt32();

			// And set the value
			SetHandle(handle);

            pIsInvalid = (HandleValue == 0 || HandleValue == -1);
		}

        public override bool IsInvalid
        {
            get 
            {
				return pIsInvalid;
            }
        }

        protected override bool ReleaseHandle()
        {
			try
			{
                return NativeMethods.CloseHandle(this);
			}
			catch
			{
				return false;
			}
            //finally
            //{
//				// Since the port is confirmed closed, delete its entry from the
//				// registry to prevent a clean-up attempt when the app is next run.
//				RegistryKey SerialHandlesKey = Registry.LocalMachine.OpenSubKey(@"Software\GeoFrameworks\Open Serial Handles", true);
//				// Anything to do?
//				if(SerialHandlesKey != null)
//				{
//					try
//					{
//						string HandleValue = pHandle.ToString();
//						object Value = SerialHandlesKey.GetValue(HandleValue);
//						if(Value != null)
//							SerialHandlesKey.DeleteValue(HandleValue);
//					}
//					catch
//					{
//						// Ignore
//					}
//					finally
//					{
//						SerialHandlesKey.Close();
//					}
//				}
            //}
        }

//        public static implicit operator SafeFileHandle(IntPtr value)
//        {
//            return new SafeFileHandle(value);
//        }
//
//        public static implicit operator IntPtr(SafeFileHandle value)
//        {
//            return value.DangerousGetHandle();
//        }

		public override string ToString()
		{
			return handle.ToString() + " ("
				+ (IsInvalid ? "Invalid" : "Valid")
				+ ", "
				+ (IsClosed ? "Closed" : "Open")
				+ ")";
		}
    }
}
